/* serial.c -- cheap serial dumper
**
** Copyright 2006, Brian Swetland.  All rights reserved.
** See provided LICENSE file or http://frotz.net/LICENSE for details.
*/

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <sys/fcntl.h>
#include <errno.h>

int text2speed(const char *s)
{
    int n = atoi(s);
    switch(n){
    case 115200:
        return B115200;
    case 38400:
        return B38400;
    case 19200:
        return B19200;
    case 9600:
        return B9600;
    default:
        return B115200;
    }    
}

int openserial(const char *device, int speed)
{
	struct termios tio;
	int fd;
	if((fd = open(device, O_RDWR | O_NOCTTY)) < 0) return -1;

	memset(&tio, 0, sizeof(tio));
//	tcgetattr( fd, &tio);
#ifdef __FreeBSD__
	tio.c_cflag = CS8 | CLOCAL | CREAD;
	tio.c_ispeed = speed;
	tio.c_ospeed = speed;
#else
	tio.c_cflag = speed | CS8 | CLOCAL | CREAD;
#endif
	tio.c_iflag = IGNPAR;
	tio.c_lflag = 0; /* turn of CANON, ECHO*, etc */
	tio.c_cc[VTIME]    = 0;
	tio.c_cc[VMIN]     = 1;
	tcsetattr( fd, TCSANOW, &tio );
	tcflush( fd, TCIFLUSH );
	return fd;
}

int main(int argc, char *argv[])
{
    int speed = B19200;
    const char *device = "/dev/ttyUSB0";
    int fd;
    int textmode = 1;
    char command[256];

    command[0] = 0;
 
    while(argc > 1){
        strcat(command, argv[1]);
	strcat(command, " ");
        argc--;
        argv++;
    }
    strcat(command, "\n");

    fd = openserial(device, speed);
    if(fd < 0){
        fprintf(stderr,"cannot open '%s'\n", device);
        return -1;
    }

    write(fd, command, strlen(command));

    for(;;){
        unsigned char x;
        if(read(fd, &x, 1) == 1){
            if(textmode){
                if((x >= ' ') && (x < 127)){
                    printf("%c", x);
                } else if((x == 10) || (x == 13)){
                    printf("%c", x);
                } else {
                    printf(".");
                }
            } else {
                printf("%02x %c ",x,((x >= ' ') && (x < 127)) ? x : '.');
            }
            fflush(stdout);
            if(x == 10) break;
        }
    }
    close(fd);
    return 0;
}
